<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>葫芦养生 - APP下载</title>
    <!-- 微信分享配置 -->
    <meta property="og:title" content="葫芦养生 - APP下载">
    <meta property="og:description" content="葫芦养生APP，健康生活从这里开始">
    <meta property="og:image" content="https://app.hoolohealth.com/test-socialmedia/assets/background.png">
    <meta property="og:url" content="https://app.hoolohealth.com/test-socialmedia">
    <!-- 添加 UA 解析库 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/UAParser.js/1.0.37/ua-parser.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            min-height: 100vh;
            text-align: center;
            position: relative;
            overflow: hidden;
        }

        body {
            /* position: fixed; */
            /* top: 0; */
            /* left: 0; */
            width: 100%;
            height: 100%;
            background-image: url('assets/background.png');
            /* background-size: 100% 100%; */
            background-size: cover;

            /* background-position: center; */
            background-repeat: no-repeat;
            /* z-index: -1; */
        }

        #ipdisp {
            position: absolute;
            top: 64.5vh;
            left: 50%;
            transform: translateX(-50%);
            margin-bottom: 20px;
            color: #666;
        }

        #appStoreLink {
            position: absolute;
            bottom: 12%;
            /* top: 69.5vh; */
            left: 50%;
            transform: translateX(-50%);
            display: block;
            cursor: pointer;
        }

        /* iOS 设备按钮样式 */
        .ios-button {
            width: 53.33vw;
            height: auto;
        }

        /* Android 设备按钮样式 */
        .android-button {
            width: 38.13vw;
            height: 6.16vh;
        }

        .background-div {
            position: relative;
            z-index: 99;
        }
    </style>
</head>

<body>
    <!-- <div class="background-div"></div> -->
    <div id="iosContent" style="display: none;">
        <div id="ipdisp"></div>
        <a href="javascript:;" id="appStoreLink">
            <img src="" alt="App 下载" id="downloadButton">
        </a>
    </div>

    <script>
        // 微信环境检测
        function isWeChat() {
            return /micromessenger/i.test(navigator.userAgent);
        }
        if (isWeChat()) {
            // 保留所有参数
            var search = window.location.search;
            window.location.href = 'simple-wechat-guide.html' + search;
        }
    </script>

    <script>
        // 设备检测
        const parser = new UAParser();
        const os = parser.getOS();
        const browser = parser.getBrowser();
        const isIOS = os.name === "iOS";
        // const isWeChat = browser.name === "WeChat" || /micromessenger/i.test(navigator.userAgent); // 删除这行
        // 后续如需判断微信环境，统一用 isWeChat() 函数

        // 设置背景图片
        const backgroundDiv = document.querySelector('body');
        backgroundDiv.style.backgroundImage = isIOS
            ? "url('assets/background.png')"
            : "url('assets/android-background.png')";

        // 如果是iOS设备且不在微信中，显示下载按钮和链接
        if (isIOS && !isWeChat()) {
            document.getElementById('iosContent').style.display = 'block';

            // 设置下载按钮图片和样式
            const downloadButton = document.getElementById("downloadButton");
            downloadButton.src = "assets/btn_download_appstore.png";
            downloadButton.alt = "App Store 下载";
            downloadButton.className = "ios-button";

            const ipdisp = document.getElementById("ipdisp");
            const appStoreLink = document.getElementById("appStoreLink");

            // 添加点击事件处理
            appStoreLink.onclick = async (event) => {
                event.preventDefault();

                const urlParams = new URLSearchParams(window.location.search);
                const adId = urlParams.get("adId");
                const appId = urlParams.get("appId") || "bXS7a2v3fgRW6U7O";
                const baseHost = "https://ancientcare.yueliangmob.com/app/testenv";

                try {
                    // 1. 获取落地页信息（必须成功才能跳转）
                    const detectResponse = await fetch(
                        `${baseHost}/h5/getLandingPagerMsg`, {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({
                            api: "h5/getLandingPagerMsg",
                            caller: appId,
                            param: { adId, appId, channelType: "socialMedia" },
                            requestId: "ABCD1234",
                            time: new Date().getTime(),
                            traceId: "2002271818562848300",
                        }),
                    });

                    if (!detectResponse.ok) throw new Error(`获取失败，状态码：${detectResponse.status}`);
                    const { data } = await detectResponse.json();
                    const appStoreUlr = data.appStoreUlr;
                    const monitorUrl = data.monitorUrl;

                    // 2. 处理上报参数（同步操作）
                    const processedUrl = monitorUrl
                        .replace("__TS__", new Date().getTime())
                        .replace("__SYS_VERSION__", encodeURIComponent(`${os.name} ${os.version}`));
                    console.log("🚀 => processedUrl:", processedUrl)

                    // 关键优化：使用 sendBeacon 发送上报（异步非阻塞，页面跳转时仍会发送）
                    fetch(processedUrl, {
                        method: 'GET',
                        keepalive: true  // 保持连接确保页面卸载时仍能发送
                    });

                    // 3. 当前页面跳转（用户无需返回）
                    if (appStoreUlr) {
                        // 尝试多种跳转方式
                        try {
                            // 方式1：直接跳转
                            window.location.href = appStoreUlr;
                        } catch (e) {
                            // 方式2：使用window.open
                            window.open(appStoreUlr, '_blank');
                        }
                    } else {
                        throw new Error("appStoreUlr 为空");
                    }
                } catch (error) {
                    console.error("下载流程失败:", error);
                    // 显示错误提示
                    alert("下载失败，请稍后重试");
                }
            };
        }

        // 调试信息
        console.log("设备信息:", {
            os: os.name,
            osVersion: os.version,
            browser: browser.name,
            browserVersion: browser.version,
            isIOS: isIOS,
            isWeChat: isWeChat()
        });
    </script>
</body>

</html>